/* textmodify.c - part of ziproxy package
 * 2002 Juraj Variny<variny@naex.sk>
 *
 * Released subject to GNU General Public License
 *
 * HTML modification, text compression fuctions
 */

#include <string.h>
#include <stdlib.h>
#include <unistd.h> //for off_t
#include <regex.h>
#include <assert.h>

#ifdef GZIP
#include <zlib.h>
#endif

int undo_name (char *path)
{
		char * tempp;

		tempp = strrchr(path,'.');

		if(tempp && (!strcasecmp(tempp,".gif_or_jpg") || !strcasecmp(tempp,".png_or_jpg")))
		{
				tempp[4]=0;
				//copy the arguments + NUL (can't strcpy, because TO and FROM overlap)
//				memmove(tempp + 4,tempp + 11,strlen(tempp)-10);
				return 1;
		}
		
		return 0;
}

//inbuf needs to be null-terminated!				
int modify_img_src(char* inbuf, char** outbuf)
{
//		const char reg_exp_str[] = "<[^<>]\\+\\(src\\|href\\|background\\) *= *\\\"\\?[^\"<>]\\+\\(\\.gif\\|\\.png\\)\"\\?[^<>]*>";
		//const char reg_exp_str[] = "<[^<>]+(src|href|background) *= *\"?[^\"<>]+(\\.gif|\\.png)\"?[^_\?<>]*>";
		const char reg_exp_str[] = "<[^<>]+(src|href|background) *= *[\"']?[^\"<>]+"
				"(\\.gif|\\.png)[\"']?( *>| [^<>]+>)";
		regex_t expr;
		regmatch_t match[3];
		int offs = -1 ,status,len,tmp;
		char *srcp=inbuf,*destp;

		status = regcomp(&expr, reg_exp_str, REG_ICASE | REG_EXTENDED);

		assert(!status);


		while(!(status = regexec(&expr, srcp, 3, match, 0)))
		{
				if(offs < 0)
				{
					len = strlen(inbuf)*1.1;
					*outbuf = malloc(len);
					destp = *outbuf;
				}
				
				offs = match[2].rm_eo; 

				if(destp - *outbuf + 8 + match[0].rm_eo > len)
				{
						tmp = destp - *outbuf;
						*outbuf = realloc(*outbuf,len*=1.5 + 1);
						destp = *outbuf + tmp;
				}

				memcpy(destp, srcp, offs);
				srcp += offs;
				destp += offs;
				memcpy(destp, "_or_jpg", 7);
				destp += 7;
				offs = match[0].rm_eo - offs;
				if(offs)
				{
						memcpy(destp, srcp, offs);
						srcp += offs;
						destp += offs;
				}
		}
		if(offs >= 0)
		{
				strcpy(destp,srcp);
				tmp = 1;
				free(inbuf);
		}
		else 
		{
				*outbuf = inbuf;
				tmp = 0;
		}
		if(status == REG_ESPACE)
				status = tmp + 2;
		else
				status = tmp;

		return status;
}

#ifdef GZIP
int gzip(char* inbuf, int inlen, char** outbuf, int *outlen)
{
		int filedes;
		char filenam[] = "/tmp/ziproxy_XXXXXX";
		gzFile gzfile;

		if((filedes = mkstemp(filenam)) < 0) return 10;
		unlink(filenam);
		if(!(gzfile = gzdopen(dup(filedes), "w9"))) return 20;
		if(!(gzwrite(gzfile, inbuf, inlen)))
		{
				gzclose(gzfile);
				return 30;
		}
		
		if(gzclose(gzfile) != Z_OK) return 40;

		free(inbuf);

		*outlen=lseek(filedes,0,SEEK_END);
		*outbuf = allocstr(*outlen);
		
		lseek(filedes,0,SEEK_SET);

		//read gz file
		read(filedes,*outbuf, *outlen);
		close(filedes);
		return 0;
}
#endif

